import { Inject, Injectable } from '@nestjs/common'
import { plainToInstance } from 'class-transformer'
import { RedisService } from 'src/redis/redis.service'

import { MapDTO } from './map.dto'

@Injectable()
export class MapService {
  constructor(@Inject(RedisService) private readonly redisService: RedisService) {}

  async save(data: MapDTO[]) {
    const self = this

    await Promise.all(
      data.map(function (item) {
        return self.redisService.client.geoadd('map', item.lng, item.lat, item.title)
      })
    )
  }

  near(pos: [string, string], radius: number) {
    return this.redisService.client
      .georadius('map', pos[0], pos[1], radius, 'km', 'withcoord', 'ASC')
      .then(function (data) {
        return data.map(function (item) {
          const [title, pos] = item as [string, [string, string]]
          return plainToInstance(MapDTO, { lng: pos[0], lat: pos[1], title })
        })
      })
  }
}
